// pages/home/home.js
var util = require('../../utils/util.js')
var upFiles = require('../../utils/upFiles.js')
var config = require('../../utils/config.js')

var app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productName: util.productName(),
    productNameIndex: 0,
    productName1: "请输入",
    date: "2018-01-21",
    files: [],
    upFilesBtn: true,
    upFilesProgress: false,
    maxUploadLen: 4,
    feedback: "",
    userphone: "",
    textareaLength: "0/200",
    upImgArr: "",
    date_picker_end: util.getNowTime()
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    var that = this;
    wx.showLoading({
      title: '更新数据',
      mask: true
    })

    app.login(function(result) {
      var phoneNumber = wx.getStorageSync('phoneNumber');
      if (phoneNumber != "") {
        wx.hideLoading();
        app.globalData.phoneNumber = phoneNumber;
      } else {
        util.getOpenId(result, function(openId) {
            // 成功就获取手机号码,然后跳转登录页面
            util.getPhoneNumber(openId,
              function(successResult) {
                // 获取到了手机号码,
                wx.hideLoading();
                wx.setStorageSync('phoneNumber', successResult);
              },
              function(failedResult) {
                // 获取手机号码失败,跳转绑定页面
                that.navigateToBind();
              });
          }),
          function(fail) {
            that.navigateToBind();
          }
      }
    });

  },
  navigateToBind: function() {
    wx.hideLoading();
    wx.navigateTo({
      url: '../bind/bindPhone'
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },
  feedback: function(e) {
    var value = e.detail.value;
    var feedbackLength = value.length;
    this.setData({
      feedback: value,
      textareaLength: feedbackLength + "/200"
    })
  },
  userphone: function(e) {
    this.setData({
      userphone: e.detail.value
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  bindCountryChange: function(e) {
    var index = e.detail.value;
    var abc = this.data.productName[index];

    this.setData({
      productNameIndex: index,
      productName1: abc
    })
  },
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },
  chooseImage: function(e) {
    // 这边获取图片的个数
    var that = this;
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function(res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.setData({
          files: that.data.files.concat(res.tempFilePaths)
        });
      }
    })
  },
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  uploadFiles: function(e) {
    // 上传视频
    var that = this;
    wx.showActionSheet({
      itemList: ['选择图片', '选择视频'],
      success: function(res) {
        var index = res.tapIndex;
        if (index == 0) {
          upFiles.chooseImage(that, that.data.maxUploadLen)
        } else {
          upFiles.chooseVideo(that, that.data.maxUploadLen)
        }

      },
      fail: function(res) {

      }
    })
  },
  delFile: function(e) {
    // 删除视频
    var that = this;
    wx.showModal({
      title: '提示',
      content: '您确认删除嘛？',
      showCancel: true,
      success: function(res) {
        if (res.confirm) {
          // 点击了确定
          var delIndex = e.currentTarget.dataset.index;
          var delType = e.currentTarget.dataset.type;
          let upImgArr = that.data.upImgArr;
          let upVideoArr = that.data.upVideoArr;

          if (delType == 'image') {
            upImgArr.splice(delIndex, 1)
            that.setData({
              upImgArr: upImgArr
            })
          } else if (delType = 'video') {
            upVideoArr.splice(delIndex, 1)
            that.setData({
              upVideoArr: upVideoArr,
            })
          }
          let upFilesArr = upFiles.getPathArr(that);
          if (upFilesArr.length < that.data.maxUploadLen) {
            that.setData({
              upFilesBtn: true
            })
          }

        } else if (res.cancel) {
          // 点击了取消

        }
      },
      fail: function(res) {},
    })
  },
  subFormData: function(e) {
    var checkResult = this.checkUploadData();
    if (!checkResult) {
      return
    }

    wx.showLoading({
      title: '正在上传...',
      mask: true,
    })

    let that = this;
    let upData = {};

    let upImgArr = that.data.upImgArr;
    let upVideoArr = that.data.upVideoArr;

    this.setData({
      upFilesProgress: true,
    })

    upData['url'] = config.service.upFiles;
    upFiles.upFilesFun(this, upData, function(res) {
        if (res.index < upImgArr.length) {
          upImgArr[res.index]['progress'] = res.progress

          that.setData({
            upImgArr: upImgArr,
          })
        } else {
          let i = res.index - upImgArr.length;
          upVideoArr[i]['progress'] = res.progress
          that.setData({
            upVideoArr: upVideoArr,
          })
        }
      },
      function(arr) {
        var str = arr;
        // 上传完成, 进行文字的上传
        that.uploadText(str);
      });
  },
  uploadText: function(arr) {
    var that = this;

    // 获取问题反馈
    var feedback = that.data.feedback;
    var isEmojiCharacter = util.isEmojiCharacter(feedback);
    if (isEmojiCharacter) {
      wx.showToast({
        title: '请勿上传非法字符',
        icon: 'none',
        duration: 1000,
        mask: true,
      })
      return;
    }

    // 获取产品名称
    var productName = (that.data.productName[that.data.productNameIndex]).substring(0, 4);
    var productIndex = this.getproductIndex(productName);
    console.log(productIndex);

    // 获取购买日期
    var de = that.data.date;
    de = new Date(de).getTime();
    // 获取登录账号
    var userphone = that.data.userphone;

    // 先判断是否为空
    var url = config.service.userFeedback;

    var imagesStr = "";
    for (var i = 0; i < arr.length; i++) {
      imagesStr += arr[i].path + ",";
    }

    imagesStr = imagesStr.substr(0, imagesStr.length - 1);

    wx.request({
      url: url,
      data: {
        timestamp: 12345678,
        sign: "0271733ec529d0608c8a0e719df2282e",
        username: app.globalData.phoneNumber,
        content: feedback,
        platform: 6,
        images: imagesStr,
        saletime: de / 1000,
        account: userphone,
        product_name: productIndex
      },
      method: 'GET',
      dataType: 'json',
      success: function(res) {

        wx.hideLoading();

        var code = res.data.code;
        if (code == 200) {
          // 跳转上传成功页面
          //判断是否有打开过页面
          wx.navigateTo({
            url: '../success/submitSucc',
            success: function(res) {
              that.setData({
                feedback: "",
                userphone: "",
                textareaLength: "0/200",
                date: "2018-01-21",
                productNameIndex: 0,
                productName1: "请输入",
                upFilesProgress: false,
                upImgArr: [],
                upVideoArr: [],
                upFilesBtn: true,
              });
            }
          })
        } else {
          var errorText = res.data.message;
          wx.showToast({
            title: errorText,
            icon: 'none',
            duration: 1500,
            mask: true,
            complete: function(res) {
              that.setData({
                upFilesProgress: false,
              });
            },
          })
        }
      },
      fail: function(res) {

        wx.hideLoading();

      },
      complete: function(res) {
        // 重置所有的
      },
    })
  },
  checkUploadData: function(e) {
    var that = this;
    // 获取问题反馈
    var feedback = that.data.feedback;
    var feedbackLength = feedback.length;

    if (feedbackLength < 10) {
      wx.showToast({
        title: '问题反馈内容不得小于10个字',
        icon: 'none',
        duration: 3000
      });

      return false;
    }

    // 获取问题反馈
    var isEmojiCharacter = util.isEmojiCharacter(feedback);
    if (isEmojiCharacter) {
      wx.showToast({
        title: '请勿上传非法字符',
        icon: 'none',
        duration: 1000,
        mask: true,
      })
      return false;
    }


    // 获取产品名称
    var productName = that.data.productName[that.data.productNameIndex];
    if (this.data.productName1 == "请输入") {
      wx.showToast({
        title: '请输入产品名称',
        icon: 'none',
        duration: 3000
      });

      return false;
    }

    // 获取购买日期
    var de = that.data.date;

    // 获取登录账号
    var userphone = that.data.userphone;
    if (userphone == '' || userphone.length < 11) {
      wx.showToast({
        title: '请输入登录账号',
        icon: 'none',
        duration: 3000
      });

      return false;
    }
    return true;
  },
  getproductIndex: function(productName) {
    // 1-H001，3-H003,4-H005 4-H004

    switch (productName) {
      case "H001":
        return 1;
      case "H003":
        return 3;
      case "H004":
        return 4;
      case "H005":
        return 5;
    }

    return 1;
  }
})